package com.marchsoft.group.manager.security.handler;

import com.alibaba.fastjson.JSON;
import com.marchsoft.group.manager.common.response.Result;
import com.marchsoft.group.manager.security.Utils.JwtUtils;
import com.marchsoft.group.manager.security.entity.SecurityUserDetails;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * fetch
 * @Author zhanghaoqi
 * @Description  登陆成功的处理类
 * @Data 9:58 2020/12/19
 */
@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {


    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication)
            throws IOException, ServletException {
        System.out.println("登录成功");
        httpServletResponse.setContentType("application/json");
        httpServletResponse.setCharacterEncoding("UTF-8");

        //从authentication中获取用户信息
    SecurityUserDetails userDetail = (SecurityUserDetails) authentication.getPrincipal();
        //生成jwt
        System.out.println(userDetail.getUsername());


        String token =  JwtUtils.createJwtToken(userDetail.getUsername());
        System.out.println(token);
        httpServletResponse.addHeader("token", "Bearer " + token);
        httpServletResponse.getWriter().write(JSON.toJSONString(Result.success(token)));
        httpServletResponse.getWriter().flush();
    }
}
